<template>
  <div>
    <van-popup :show="showPicker" round position="bottom">
      <div v-if="diffCauseIndex == 5">
        <van-field
            v-model="otherDiffCause"
            maxlength="128"
            label="其他差异原因"
            placeholder="点击此处输入"
        />
      </div>
      <van-picker
          :columns="diffCauseArray"
          v-model="pickItem"
          @confirm="pickerConfirm"
          @cancel="$emit('cancel')"
          @change="updateDiffCauseIndex"
      >
      </van-picker>
    </van-popup>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {showToast} from 'vant'

defineProps({
  showPicker: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['cancel'])

const otherDiffCause = ref('')
const pickItem = ref([])
const diffCauseIndex = ref(0)
const model = defineModel({default: '照片猪只遮挡'})
const diffCauseArray = [
  {text: '照片猪只遮挡', value: '照片猪只遮挡'},
  {text: '栏位太大拍不全', value: '栏位太大拍不全'},
  {text: '相机无广角拍不全', value: '相机无广角拍不全'},
  {text: '光线导致照片不清晰', value: '光线导致照片不清晰'},
  {
    text: '技术原因（照片肉眼能分辨，算法识别错误）',
    value: '技术原因（照片肉眼能分辨，算法识别错误）'
  },
  {text: '其他', value: '其他'}
]

onMounted(() => {
  // 初始化
  let index = diffCauseArray.findIndex((i) => i.value == model.value)

  if (model.value == '') {
    pickItem.value[0] = '照片猪只遮挡'
  } else if (index == -1) {
    pickItem.value[0] = '其他'
    otherDiffCause.value = model.value
    diffCauseIndex.value = 5
  } else {
    pickItem.value[0] = model.value
    diffCauseIndex.value = index
  }
})

const updateDiffCauseIndex = () => {
  let index = diffCauseArray.findIndex((i) => i.value == pickItem.value[0])

  if (index == -1) {
    diffCauseIndex.value = 5
  } else {
    diffCauseIndex.value = index
  }
}

const pickerConfirm = () => {
  if (diffCauseIndex.value == 5 && otherDiffCause.value == '') {
    showToast('请填写差异原因')
  } else {
    if (diffCauseIndex.value === 5 && !otherDiffCause.value.startsWith('其他-')) {
      model.value = '其他-' + otherDiffCause.value
    } else if (diffCauseIndex.value === 5) {
      model.value = otherDiffCause.value
    } else {
      model.value = pickItem.value[0]
    }
    // 触发关闭事件
    emit('cancel')
  }
}
</script>

<style lang="less" scoped></style>
